<!-- 月统计表 -->
<template>
  <div class="month-table">
    <!-- 查询 -->
    <el-form :model="formData" size="mini" :inline="true" class="demo-form-inline">
      <el-row :gutter="15">
        <el-col :span="20">
          <el-form-item label="客户" label-width="40px">
            <el-select filterable v-model="formData.clientId" @change="changeTable" @visible-change="selectStar" placeholder="请选择客户">
              <el-option v-for="(item, index) in userInfo" :key="index" :label="item.search" :value="item.UserId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="船公司" label-width="60px">
            <el-select filterable v-model="formData.boatAgentId" @change="changeTable" @visible-change="selectBoat" placeholder="请选择船公司">
              <el-option v-for="(item, index) in boatList" :key="index" :label="item.nameCn" :value="item.boatComId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="业务员" label-width="60px">
            <el-select filterable v-model="formData.theOperatorId" @change="changeTable" @visible-change="selectMan" placeholder="请选择业务员">
              <el-option v-for="(item, index) in salesman" :key="index" :label="item.fullName" :value="item.salesmanId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" label-width="40px">
            <el-select v-model="formData.boxState" @change="changeTable" placeholder="请选择状态">
              <el-option v-for="(item, index) in boxTate" :key="index" :label="item.lable" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" label-width="70px">
            <el-date-picker
              v-model="formData.applyStartTime"
              class="time-small"
              align="right"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="开始时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-date-picker
              v-model="formData.applyEndTime"
              class="time-small"
              align="right"
              type="date"
              @change="changeTable"
              value-format="yyyy-MM-dd"
              placeholder="结束时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <div style="display: flex; justify-content: flex-end;">
            <el-button type="primary" @click="getMonth(1, 15)" size="mini">搜索</el-button>
            <el-button size="mini" @click="clearMonth">清空</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <!-- 操作 -->
    <el-row>
      <el-form size="mini" :inline="true" class="demo-form-inline">
        <el-form-item>
          <!-- <el-button type="warning" size="mini">打印</el-button> -->
          <!-- <el-button size="mini" @click="checkExport()">导出</el-button> -->
          <el-button size="mini" @click="checkExport()">导出</el-button>
          <download-excel
            id="monthtable"
            v-show="false"
            :header="excelTitle"
            :data="mydata"
            :fields="myobj"
            name="月统计表">
          </download-excel>
          <el-button size="mini" @click="exportData()">导出全部</el-button>
          <el-select v-model="excelStyle" placeholder="">
            <el-option label="默认样式" value="0"></el-option>
            <el-option label="只有总费用样式" value="1"></el-option>
            <el-option label="有船名航次总费用样式" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-row>
    <!-- 表格 -->
    <el-table
      v-loading="loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(255, 255, 255, 0.5)" border :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center" width="50"></el-table-column>
      <el-table-column
        v-for="item in myList"
        :prop="item.props"
        :key="item.id"
        align="center"
        :label="item.field">
      </el-table-column>
    </el-table>
    <div class="chargeable_table_pagination">
      <el-pagination
        @current-change="handleCurrentChange"
        :page-size="numb"
        @size-change="handleSizeChange"
        :page-sizes="[10, 15, 20]"
        :current-page.sync="pageNo"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {
  dayStatistics,
  getSalesman,
  boatCompanyList,
  SearchUserInfo,
  // exportData,
  statisticsDerived
} from './api/finance'
import {
  GetUserProfile
} from '../cpInfoMan/api/customerManagement'
export default {
  data () {
    return {
      tableData: [],
      mydata: [],
      formData: {
        clientId: '',
        boatAgentId: '',
        theOperatorId: '',
        boxState: '',
        applyStartTime: this.formatDate(new Date(new Date().getFullYear(), new Date().getMonth(), 1)),
        applyEndTime: this.formatDate(new Date())
      },
      boxTate: [
        {lable: '全部', value: ''},
        {lable: '已完成', value: 2},
        {lable: '已对单', value: 16}
      ],
      myList: [
        { field: '客户', props: 'clientName' },
        { field: '箱量', props: 'num' },
        { field: '总计', props: 'sumMoney' }
      ],
      myobj: {
        // clientName: '客户',
        // num: '箱量',
        // sumMoney: '总计'
      },
      excelStyle: '0',
      myuser: {},
      excelTitle: [],
      boatList: [],
      userInfo: [],
      salesman: [],
      multipleSelection: [],
      pageNo: 1,
      numb: 15,
      loading: true,
      total: 0
    }
  },
  mounted () {
    this.getMonth(1, 15)
    this.getSalesman()
    this.myuserInfo()
    this.SearchBoatAgentComData()
    this.SearchUserInfo()
  },
  methods: {
    // 获取月统计表
    async getMonth (pg, nb) {
      this.loading = true
      const res = await dayStatistics({
        page: pg,
        num: nb,
        clientId: this.formData.clientId,
        boatAgentId: this.formData.boatAgentId,
        theOperatorId: this.formData.theOperatorId,
        boxState: this.formData.boxState,
        applyStartTime: this.formData.applyStartTime || '',
        applyEndTime: this.formData.applyEndTime || ''
      })
      if (res.status === 200) {
        this.tableData = res.data
        this.mydata = res.data
        let mobj = this.tableData[0]
        let myObj = {}
        let feeList = []
        if (this.tableData.length !== 0 && this.myList.length === 3) {
          for (var key in mobj) {
            if (mobj.hasOwnProperty(key) === true && mobj[key].name) {
              myObj = { field: mobj[key].name, props: key + '.' + 'money' }
              feeList.push(myObj)
            }
          }
          feeList.map((item) => {
            this.myList.splice(2, 0, item)
          })
          this.myList.map(item => {
            this.myobj[item.field] = item.props
          })
        }
        if (res.dataCount) {
          this.total = parseInt(res.dataCount)
        } else {
          this.total = 0
        }
        if (nb === 10000) {
          this.exportAll(res.data)
        }
        this.loading = false
      } else {
        this.$notify({
          title: '错误',
          message: res.msg,
          type: 'error'
        })
        this.loading = false
      }
    },
    // 获取业务员列表
    async getSalesman () {
      const res = await getSalesman({})
      if (res.status === 200) {
        this.salesman = res.data
      } else {
        this.$notify({
          title: '错误',
          message: res.msg,
          type: 'error'
        })
      }
    },
    // 获取船代公司列表
    async SearchBoatAgentComData () {
      const res = await boatCompanyList({})
      if (res.status === 200) {
        this.boatList = res.data
      } else {
        this.$notify({
          title: '错误',
          message: res.msg,
          type: 'error'
        })
      }
    },
    // 获取客户信息
    async SearchUserInfo () {
      const res = await SearchUserInfo({})
      if (res.status === 200) {
        this.userInfo = res.data
      } else {
        this.$notify({
          title: '错误',
          message: res.msg,
          type: 'error'
        })
      }
    },
    // 获取账号信息
    async myuserInfo () {
      const res = await GetUserProfile({})
      if (res.status === 200) {
        this.myuser = res.data[0]
        this.excelTitle = [
          this.myuser.companyName,
          '公司地址: ' + this.myuser.address,
          '公司电话: ' + this.myuser.mobile + '  ' + '公司传真: ' + this.myuser.fax
        ]
      } else {
        this.$notify({
          title: '错误',
          message: res.msg,
          type: 'error'
        })
      }
    },
    // 转换日期
    formatDate (date) {
      var y = date.getFullYear()
      var m = date.getMonth() + 1
      m = m < 10 ? '0' + m : m
      var d = date.getDate()
      d = d < 10 ? ('0' + d) : d
      return y + '-' + m + '-' + d
    },
    // change事件
    changeTable () {
      this.getMonth(1, 15)
    },
    // 页数
    handleCurrentChange (val) {
      this.getMonth(val, this.numb)
      this.pageNo = val
    },
    // 每页条数
    handleSizeChange (val) {
      this.getMonth(this.pageNo, val)
      this.numb = val
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    exportExcel () {
      if (this.mydata.length === 0) {
        return false
      }
      var that = this
      setTimeout(function () {
        document.getElementById('monthtable').click()
        that.getMonth(that.pageNo, that.numb)
      }, 500)
    },
    // 全部导出
    exportAll () {
      this.exportExcel()
    },
    // 选中导出
    checkExport () {
      let len = this.tableData.length
      if (len === 0) {
        this.$message({
          message: '没有数据，请添加数据后再导出！',
          type: 'warning'
        })
        return false
      }
      this.excelTitle[3] = '时间: ' + this.formData.applyStartTime + ' / ' + this.formData.applyEndTime
      if (this.multipleSelection.length === 0) {
        this.exportAll()
      } else {
        this.mydata = this.multipleSelection
        this.exportExcel()
      }
    },
    // // 全部导出
    // exportAll (dt) {
    //   let mydata = []
    //   let mobj = this.tableData[0]
    //   for (var key in mobj) {
    //     if (mobj.hasOwnProperty(key) === true && mobj[key].name) {
    //       this.myobj[key] = mobj[key].name
    //     }
    //   }
    //   mydata = dt
    //   mydata.map((item) => {
    //     for (var index in item) {
    //       if (item.hasOwnProperty(index) === true && item[index].name) {
    //         item[index] = item[index].money
    //       }
    //     }
    //   })
    //   mydata.unshift(this.myobj)
    //   console.log(mydata)
    //   this.exportData_2(mydata)
    // },
    // // 选中导出
    // checkExport () {
    //   let mydata = []
    //   let len = this.tableData.length
    //   let mobj = this.tableData[0]
    //   for (var key in mobj) {
    //     if (mobj.hasOwnProperty(key) === true && mobj[key].name) {
    //       this.myobj[key] = mobj[key].name
    //     }
    //   }
    //   if (len === 0) {
    //     this.$message({
    //       message: '没有数据，请添加数据后再导出！',
    //       type: 'warning'
    //     })
    //     return false
    //   }
    //   if (this.multipleSelection.length === 0) {
    //     this.getMonth(1, 10000)
    //   } else {
    //     mydata = this.multipleSelection
    //     mydata.map((item) => {
    //       for (var index in item) {
    //         if (item.hasOwnProperty(index) === true && item[index].name) {
    //           item[index] = item[index].money
    //         }
    //       }
    //     })
    //     mydata.unshift(this.myobj)
    //     this.exportData_2(mydata)
    //   }
    // },
    // // 导出数据到Excel
    // async exportData_2 (mdt) {
    //   const res = await exportData({
    //     jsonStr: JSON.stringify(mdt), // JSON字符串
    //     sheetName: '月统计表', // 表名
    //     comName: this.myuser.companyName, // 公司名称
    //     comPhone: this.myuser.mobile, // 公司电话
    //     comFax: this.myuser.fax // 公司传真
    //   })
    //   if (res.status === 200) {
    //     this.$notify({
    //       title: '成功',
    //       message: res.msg,
    //       type: 'success'
    //     })
    //     window.location.href = res.data[0].path
    //     this.getMonth(1, 15)
    //   } else {
    //     this.$notify({
    //       title: '错误',
    //       message: res.msg,
    //       type: 'error'
    //     })
    //   }
    // },
    // 导出数据到Excel
    async exportData () {
      const loading = this.$loading({
        lock: true,
        text: '正在导出数据请稍后!',
        spinner: 'el-icon-loading',
        background: 'rgba(255,255,255,0.5)',
        target: '.inner-container', // 需要遮罩的区域
        body: false
      })
      const res = await statisticsDerived({
        clientId: this.formData.clientId, // 客户编号
        boatAgentId: this.formData.boatAgentId, //  船公司编号
        theOperatorId: this.formData.theOperatorId, //  业务员编号
        boxState: this.formData.boxState,
        applyStartTime: this.formData.applyStartTime, //  申请开始时间
        applyEndTime: this.formData.applyEndTime, //  申请结束时间
        styleType: this.excelStyle,
        page: this.pageNo, //  页数
        num: this.numb //  条数
      })
      if (res.status === 200) {
        this.$notify({
          title: '成功',
          message: res.msg,
          type: 'success'
        })
        loading.close()
        window.location.href = res.data[0].path
        this.getMonth(1, 15)
      } else {
        this.$notify({
          title: '错误',
          message: res.msg,
          type: 'error'
        })
        loading.close()
      }
    },
    selectStar (value) {
      let _that = this
      if (value) {
        setTimeout(function () {
          _that.SearchUserInfo()
        }, 500)
      }
    },
    selectBoat (value) {
      let _that = this
      if (value) {
        setTimeout(function () {
          _that.SearchBoatAgentComData()
        }, 500)
      }
    },
    selectMan (value) {
      let _that = this
      if (value) {
        setTimeout(function () {
          _that.getSalesman()
        }, 500)
      }
    },
    clearMonth () {
      this.formData = {
        clientId: '',
        boatAgentId: '',
        theOperatorId: '',
        boxState: '',
        applyStartTime: '',
        applyEndTime: ''
      }
    }
  }
}
</script>

<style lang="less">
.month-table {
  .demo-form-inline {
    .el-input__inner {
      width: 130px;
    }
    .el-range-editor {
      width: 250px;
    }
  }
  .chargeable_table_pagination {
    width: 100%;
    margin: 0 auto;
    margin-top: 10px;
  }
  .el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: 100%;
  }
}
</style>
